package lc.数组;

import java.util.Arrays;

/**
 * @description:
 * @author: qian
 * @createDate: 2021/10/17
 */
public class Math2033_获取单值网格的最小操作数 {

    public int minOperations(int[][] grid, int x) {
        int n = grid.length;
        int m = grid[0].length;
        int[] arr = new int[n * m];
        int i = 0;
        int count = 0;
        for (int i1 = 0; i1 < grid.length; i1++) {
            for (int j = 0; j < grid[i1].length; j++) {
                arr[i] = grid[i1][j];
                i++;
            }
        }
        Arrays.sort(arr);

        if (arr.length <= 1) {
            return 0;
        } else {
            int a = arr.length / 2;
            for (int i1 = 0; i1 < arr.length; i1++) {

                if ((Math.abs(arr[a] - arr[i1])) % x != 0) {
                    return -1;
                }else {
                    count+=(Math.abs(arr[a] - arr[i1])) / x;
                }
            }
        }
        return count;
    }
}
